<template>
    <div>
        <!-- 面包屑导航区 -->
        <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/Welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>系统管理</el-breadcrumb-item>
        <el-breadcrumb-item>轮播图列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图 -->
        <el-card class="box-card">
            <!-- 搜索与添加区域 -->
        <el-row :gutter="20">
            <el-col :span="4">
                <el-button type="primary" @click="addcarouslist">添加图片</el-button>
            </el-col>
        </el-row>
        <!-- 轮播图列表区域 -->
        <el-table
            :data="carousellist"
             border stripe>
            <el-table-column
                type="index"
                label="#">
            </el-table-column>
            <el-table-column
                prop="picname"
                sortable
                label="名称">
            </el-table-column>
            <el-table-column
                label="图片">
                <template slot-scope="scope">
                <img :src="'http://120.48.37.120:9000/parttime/'+scope.row.picsrc" alt="" class="previewImg">
                </template>
            </el-table-column>
            
            <el-table-column
                prop="picsrc"
                sortable
                label="值">
            </el-table-column>
            <el-table-column
                label="操作" width="180px">
                <template slot-scope="scope">
                    <!-- 修改按钮 -->
                    <el-button type="primary" icon="el-icon-edit" 
                    size="mini" @click="showEditDialog(scope.row.id)"></el-button>
                    <!-- 删除按钮-->
                    <el-button type="danger" icon="el-icon-delete" size="mini" 
                    @click="removeUserById(scope.row.id)"></el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页区域 -->
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryInfo.pagenum"
            :page-sizes="[1, 2, 5, 10]"
            :page-size="queryInfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
            </el-pagination>
        </el-card>
        <!-- 添加轮播图的对话框 -->
        <el-dialog
        title="添加轮播图" :visible.sync="addDialogVisible"
        width="50%" @close="addDialogClosed">
        <!-- 内容主体区 -->
            <el-form :model="addForm" :rules="addFormRules" 
            ref="addFormRef" label-width="70px"  >
                <el-form-item label="名称" prop="picname">
                    <el-input v-model="addForm.picname"></el-input>
                </el-form-item>
                <el-form-item label="上传图片">
                    <el-upload
                        class="avatar-uploader"
                        :action="uploadURL"
                        :auto-upload="autoUpload"
                        name="imgFile"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addcarousel">确 定</el-button>
            </span>
        </el-dialog>
        <!--修改轮播图的对话框  -->
        <el-dialog
        title="修改轮播图"
        :visible.sync="editDialogVisible"
        width="50%" @close="editDialogClosed">
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px" class="demo-ruleForm">
                <el-form-item label="名称" prop="picname">
                    <el-input v-model="editForm.picname"></el-input>
                </el-form-item>
                <el-form-item label="上传图片">
                    <el-upload
                        class="avatar-uploader"
                        :action="uploadURL"
                        :auto-upload="autoUpload"
                        name="imgFile"
                        :show-file-list="false"
                        :on-success="edithandleAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>

            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editcarouselInfo">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
export default {
    data(){
        return {
            autoUpload:true,//自动上传
            imageUrl: '',//模型数据，用于上传图片完成后图片预览
            // 上传图片的URL地址
            uploadURL: 'http://localhost:8787/carousel/upload',
            //获取轮播图列表的参数
            queryInfo:{
                pagenum:1,
                pagesize:2
            },
            carousellist:[],
            total:0,
            //控制添加轮播图对话框的显示和隐藏
            addDialogVisible:false,
            //添加轮播图的表单数据
            addForm:{
                picname:'',
                picsrc:''
            },
            //添加表单的验证规则对象
            addFormRules:{
                picname:[
                    {required:true,message:'请输入轮播图名',trigger:'blur'},
                    {min:3,max:10,message:'轮播图名的长度在3~10之间',trigger:'blur'}
                ],
                picname:[
                    {required:true,message:'请输入图片',trigger:'blur'},
                ],
            },
            //控制修改轮播图对话框的显示与隐藏
            editDialogVisible:false,
            //查询到的轮播图信息对象
            editForm:{},
            //修改表单的验证规则
            editFormRules:{
                picname:[
                    {required:true,message:'请输入轮播图名',trigger:'blur'},
                    {min:3,max:10,message:'轮播图名的长度在3~10之间',trigger:'blur'}
                ],
                picname:[
                    {required:true,message:'请输入图片',trigger:'blur'},
                ],
            },
        }
    },
    created(){
        this.getcarousellist()
    },
    methods:{
        //文件上传成功后的钩子，response为服务端返回的值，file为当前上传的文件封装成的js对象
        handleAvatarSuccess(response, file) {
            //为模型数据imageUrl赋值 用于图片预览
            console.log(1);
            console.log(response.data)
            this.imageUrl="http://120.48.37.120:9000/parttime/"+response.data;
            //设置模型数据（图片名称），后续提交ajax请求时会提交到后台最终保存到数据库
            this.addForm.picsrc = response.data;
        },
        edithandleAvatarSuccess(response, file) {
            //为模型数据imageUrl赋值 用于图片预览
            console.log(response)
            this.imageUrl="http://120.48.37.120:9000/parttime/"+response.data;
            if(response.meta.status!=200){
                this.$message.error('上传轮播图失败')
            }
            this.$message.success('上传轮播图成功')
            //设置模型数据（图片名称），后续提交ajax请求时会提交到后台最终保存到数据库
            this.editForm.picsrc = response.data;
        },
        //上传图片之前执行
        beforeAvatarUpload(file) {
            const isLt200M = file.size / 1024 / 1024 < 200;
            if (!isLt200M) {
            this.$message.error('上传套餐图片大小不能超过 200MB!');
            }
            return isLt200M;
        },
        handleRemove(){},
        async getcarousellist(){
        const {data:res} =await this.$http.get('carousel',{params:this.queryInfo})
        if(res.meta.status!=200) return this.$message.error(res.meta.msg)
        this.carousellist=res.data.records
        this.total=res.data.total
        },
        //监听pagesize改变的事件
        handleSizeChange(newSize){
            console.log(newSize);
            this.queryInfo.pagesize=newSize
            this.getcarousellist()
        },
        //监听页码值改变的数据
        handleCurrentChange(newPage){
            //console.log(newPage);
            this.queryInfo.pagenum=newPage
            this.getcarousellist()

        },
        //监听添加轮播图对话框的关闭事件
        addDialogClosed(){
            this.$refs.addFormRef.resetFields()

        },
        //点击按钮，弹出添加
        addcarouslist(){
            this.imageUrl=''
            this.addDialogVisible=true
        },
        //点击按钮，添加新轮播图
        addcarousel(){
            this.$refs.addFormRef.validate(async valid=>{
                if (!valid) {
                    return
                }
                const {data:res} =await this.$http.post('carousel',this.addForm)
                if(res.meta.status!=201){
                    this.$message.error(res.meta.msg)
                }
                this.$message.success(res.meta.msg)
                //隐藏
                this.addDialogVisible=false
                this.getcarousellist()
            })

        },

        //展示轮播图编辑的对话框
        async showEditDialog(id){
            //console.log(id);
            const {data:res}=await this.$http.get('carousel/'+id)
            if(res.meta.status!=200){
                return this.$message.error('获取信息错误')
            }
            
            this.imageUrl="http://120.48.37.120:9000/parttime/"+res.data.picsrc
            console.log(this.imageUrl);
            this.editForm=res.data
            this.editDialogVisible=true
        },
        editDialogClosed(){
            this.$refs.editFormRef.resetFields()
        }, 
        //修改轮播图信息
        editcarouselInfo(){
            this.$refs.editFormRef.validate(async valid=>{
                if(!valid) return
                //发起请求
                const {data:res} =await this.$http.put('carousel/'+this.editForm.id,this.editForm)
                if(res.meta.status!=200){
                    this.$message.error('修改轮播图信息失败')
                }
                this.editDialogVisible = false
                this.getcarousellist()
                this.$message.success('修改轮播图信息成功')
                
            })

        },
        //删除轮播图
        async removeUserById(id){
          //弹窗
           const confirmResult =await this.$confirm('此操作将永久删除该轮播图, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
          }).catch(err=>err)
          //如果轮播图确定删除则返回字符串 confirm
          //如果轮播图取消 则cancel
            if(confirmResult!='confirm'){
                return this.$message.info('已经取消删除')
            }
            console.log('确认删除');
            const {data:res}=await this.$http.delete('carousel/'+id)
            if(res.meta.status!=200){
                return this.$message.error('删除轮播图失败')
            }
            this.$message.success('删除轮播图成功')
            this.getcarousellist()
          
        }
        
    }
    
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .previewImg {
  width: 100%;
}
</style>